using System;
using System.Drawing;
using System.Globalization;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;

namespace HWEngine
{
	[Serializable]
	public class MutationRandom : ILetterMutation
	{
		private Random rand = new Random();

		[XmlAttribute("Sx")]
		public float Sx { get; set; }

		[XmlAttribute("Sy")]
		public float Sy { get; set; }

		[XmlAttribute("Enabled")]
		public bool Enabled { get; set; }

		public MutationRandom()
		{
		}

		public MutationRandom(float sx, float sy)
		{
			Sx = sx;
			Sy = sy;
			Enabled = true;
		}

		public void Mutate(Letter s)
		{
			if (!Enabled) return;

			foreach (Line l in s.Lines)
			{
				for (int i = 0; i < l.Points.Count; i++)
				{
					PointF p = l.Points[i];
					p.X += (float) ((rand.NextDouble() - 0.5)*Sx);
					p.Y += (float) ((rand.NextDouble() - 0.5)*Sy);
					l.Points[i] = p;
				}
			}
		}

		public void LoadFromXml(XPathNavigator xml)
		{
			Sx = (float) Convert.ToDouble(xml.GetAttribute("sx", String.Empty), CultureInfo.InvariantCulture);
			Sy = (float) Convert.ToDouble(xml.GetAttribute("sy", String.Empty), CultureInfo.InvariantCulture);
			Enabled = Convert.ToBoolean(xml.GetAttribute("Enabled", String.Empty), CultureInfo.InvariantCulture);
		}

		public XmlElement SaveToXml(XmlDocument parentDoc)
		{
			XmlElement el = parentDoc.CreateElement("mutationRandom");
			el.SetAttribute("sx", Sx.ToString(CultureInfo.InvariantCulture));
			el.SetAttribute("sy", Sy.ToString(CultureInfo.InvariantCulture));
			el.SetAttribute("Enabled", Enabled.ToString());
			return el;
		}
	}
}